package org.otod.security.web;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.otod.security.domain.User;
import org.otod.security.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	@Autowired
	UserService userService;

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String showLoginForm(Model model, @ModelAttribute User user) {
		return "/security/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(Model model, @ModelAttribute User user, BindingResult errors) {
		logger.info("开始登陆");

		if (errors.hasErrors()) {
			return showLoginForm(model, user);
		}

		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword(),
				user.isRememberMe());
		try {
			SecurityUtils.getSubject().login(token);
		} catch (AuthenticationException e) {
			errors.reject("error.login.generic", "Invalid username or password.  Please try again.");
		}

		if (errors.hasErrors()) {
			return showLoginForm(model, user);
		} else {
			logger.info("登陆成功");
			return "/security/home";
		}
	}

	@RequestMapping(value = "/home")
	public String home(Model model) {
		return "/security/home";
	}

}
